package top.dopen.home.work.controller;

import cn.hutool.core.lang.Console;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.annotations.ApiIgnore;
import top.dopen.home.work.common.AccessTokenTask;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * <p>
 * 微信Oauth2.0授权认证
 * </p>
 *
 * @Auther Dopen
 * @Date 2020/8/7
 */
@ApiIgnore
@Controller
@RequestMapping("/wechat/oauth")
public class WechatOauthController {

	@Value("${wechat.oauthCode.url}")
	private String oauthCodeUrl;
	@Value("${wechat.oauthCode.redirectUrl}")
	private String redirectUrl;
	@Value("${wechat.oauthCode.userInfoUrl}")
	private String userInfoUrl;
	@Resource
	private RestTemplate template;
	@Resource
	private AccessTokenTask accessTokenTask;

	@PostConstruct
	public void init(){
		if(StringUtils.isAnyBlank(oauthCodeUrl,redirectUrl)){
			throw new NullPointerException("微信Oauth认证初始化参数错误");
		}
		try {
			redirectUrl = URLEncoder.encode(redirectUrl,"UTF-8");
			oauthCodeUrl = oauthCodeUrl.replace("REDIRECT_URI",redirectUrl);
		} catch (UnsupportedEncodingException e) {
			//TODO 待处理
			e.printStackTrace();
		}
	}

	/**
	 * 获取code，若未获取则进行重定向
	 * @param response
	 * @param model
	 * @param code
	 * @return
	 * @throws IOException
	 */
	@GetMapping("getCode")
	public String getCode(HttpServletResponse response, Model model, String code) throws IOException {
		Console.log("获取Code");
		if(StringUtils.isBlank(code)){
			Console.log("不存在Code，执行重定向，{}",oauthCodeUrl);
			response.sendRedirect(oauthCodeUrl);
			return null;
		}else{
			Console.log("获取到Code:{}",code);

			String targetUrl = userInfoUrl.replace("ACCESS_TOKEN",accessTokenTask.getAccessToken()).replace("CODE",code);

			String weChatResult = template.getForObject(targetUrl, String.class);
			JSONObject json = JSON.parseObject(weChatResult);
			if("0".equals(json.getString("errcode"))){
				Console.log("获取成功{}",json);
				model.addAttribute("errMsg","0");
				if(json.containsKey("UserId")){
					model.addAttribute("wechatUserInfoId",json.getString("UserId"));
				}else{
					model.addAttribute("wechatUserInfoId",json.getString("OpenId"));
				}
			}else{
				Console.log("获取失败{}",json);
				model.addAttribute("errMsg","获取失败，errCode："+json.getString("errcode"));
			}
		}
		//TODO 此处应该重定向
		return "index";
	}
}
